#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/04
# @Author    :breeze
# @Email     :wangbaoshan@bbdservice.com
# @File      :R33_EC_PaidBusinessBadCheck
# @Software  :PyCharm

'''eof
name:申请企业已结清业务类五级分类校验（不良类）
code:R33_EC_PaidBusinessBadCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d')
                    except:
                        return_data = None

    return return_data


def get_current_time():
    try:
        if cQexecuteTime is not None:
            return convertDataType(cQexecuteTime, "date_time")
        else:
            return datetime.datetime.now()
    except:
        return datetime.datetime.now()


def get_five_year_ago(curr_date):
    if curr_date is None:
        return (get_current_time() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")
    else:
        return (convertDataType(curr_date, "date_time") - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")


def R33_EC_PaidBusinessBadCheck():
    """
    Factor1 = 借贷账户信息单元-账户活动状态（ED01AD01）∈（2-已结清）&借贷业务种类大类（ED01AD05）不为“21”(票据贴现)，且还款表现信息段（ED01B）-五级分类（ED01BD01）∈(3(次级), 4(可疑), 5(损失), 6(违约)，if关闭日期（ED01AR03）不为空，则取在60个月内的笔数，if关闭日期（ED01AR03）为空或缺失，则不做时间限制的条件判断。
    Factor3=统计借贷账户信息单元下基本信息段(ED01A)·账户活动状态(ED01AD01)==2(已结清) and 借贷账户类型(ED01AD02) 不为“D2-贴现账户”且还款表现信息段(ED01B)五级分类(ED01BD01) ∈(3(次级),4(可疑),5(损失),6(违约))and（开立日期(ED04AR01)在60个月内）的笔数；
    Factor4=担保账户信息-担保账户信息明细单元（ED04）-在保责任信息段（ED04B）-账户活动状态（ED04BD01）=2(已结清）&五级分类（ED04BD02）∈3(次级),4(可疑),5(损失),6(违约)and基本信息段（ED04A）-担保交易业务种类细分（ED04AD03）∈06（（其他融资担保）、09（其他非融资担保）、51（信用证）、61（银行承兑汇票）、71（融资类银行保函）、72（非融资类银行保函）），if关闭日期（ED04BR02）不为空，则取在60个月内的笔数，if关闭日期（ED04BR02）为空或缺失，则不做时间限制的条件判断。
    Factor5=统计担保账户信息单元·在保责任信息段(ED04B)·账户活动状态(ED04BD01)==2(已结清) and 五级分类(ED04BD02) ∈(3(次级),4(可疑),5(损失),6(违约))and 余额(ED04BJ01)>0 &基本信息段(ED04A)·担保账户类型(ED04AD01) in(G1(融资担保账户),G2(非融资担保账户),G3(支付担保账户))and（开立日期(ED04AR01)在60个月内）的笔数；
    Factor=MAX(Factor1,Factor3,Factor4,Factor5)
    注:企业征信内所有策略数据最长取值为5年，5年定义为报告生成日期（EA01AR01）当月（含）往前推60个月，如果没有报告生成日期或条件对应表无时间标识，则不做时间限制。（时间缺失经确认使用从严规则）
    """
    data = EC_DSJ_2D['data']
    # 报告头EAA [1..1]
    EAA = getTable(data, "EAA", 1, 1)
    if EAA == [{}]:
        five_years_ago = None
    elif EAA == 0:
        five_years_ago = 0
    else:
        # 报告头信息单元EA01 [1..1]
        EA01 = getTable(EAA[0], "EA01", 1, 1)
        if EA01 == [{}]:
            five_years_ago = None
        elif EA01 == 0:
            five_years_ago = 0
        else:
            # 报告标识信息段 EA01A [1..1]
            EA01A = getTable(EA01[0], "EA01A", 1, 1)
            if EA01 == [{}]:
                five_years_ago = None
            elif EA01 == 0:
                five_years_ago = 0
            else:
                EA01AR01 = EA01A[0].get('EA01AR01')
                try:
                    five_years_ago = get_five_year_ago(EA01AR01[:10])
                except:
                    five_years_ago = None

    # factor1
    # 借贷账户信息   [1..1]
    EDA = getTable(data, "EDA", 1, 0)
    if EDA == [{}]:
        factor1 = None
    elif EDA == 0:
        factor1 = 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0, 1)
        if ED01 == [{}]:
            factor1 = None
        elif ED01 == 0:
            factor1 = 0
        else:
            factor_list1 = []
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    # 还款信息段   [1..1]
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                        factor_list1.append(None)
                    elif ED01A == 0 or ED01B == 0:
                        factor_list1.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 借贷业务种类大类   [1..1]
                        ED01AD05 = ED01A[0].get('ED01AD05')
                        # 关闭日期   [1..1]
                        ED01AR03 = ED01A[0].get('ED01AR03')
                        # 到期日期 [1..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        # 还款表现信息 [0..*]
                        ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                        last_five_class = None
                        if ED01BH == [{}]:
                            factor_list1.append(None)
                        elif ED01BH == 0:
                            factor_list1.append(None)
                        else:
                            max_date = None
                            for j in ED01BH:
                                # 五级分类   [1..1]
                                ED01BD01 = j.get('ED01BD01')
                                # 信息报告日期   [1..1]
                                ED01BR01 = convertDataType(j.get('ED01BR01'), "date_time")
                                if ED01BR01 is not None and ED01BD01 is not None:
                                    if max_date is None:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD01
                                    elif ED01BR01 > max_date:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD01

                        if ED01AD01 in null_type_list or ED01AD05 in null_type_list or last_five_class in null_type_list:
                            factor_list1.append(None)
                        else:
                            ED01AR02 = convertDataType(ED01AR02, "date_time")
                            # create_time = convertDataType(EA01AR01[:10], "date_time")
                            if ED01AD01 in ("2") and ED01AD05 not in ("21") and last_five_class in ("3", "4", "5", "6"):
                                if ED01AR03 in null_type_list:
                                    if ED01AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list1.append(1)
                                    elif five_years_ago < ED01AR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list1.append(1)
                                    else:
                                        factor_list1.append(0)
                                elif ED01AR03 not in null_type_list:
                                    ED01AR03 = convertDataType(ED01AR03, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list1.append(1)
                                    elif ED01AR03 not in null_type_list:
                                        if five_years_ago < ED01AR03.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list1.append(1)
                                        else:
                                            factor_list1.append(0)
                                    else:
                                        factor_list1.append(0)
                                else:
                                    factor_list1.append(0)
                            else:
                                factor_list1.append(0)
                except:
                    factor_list1.append(None)
                    continue
            factor = [i for i in factor_list1 if i is not None]
            # factor = filter(lambda x: x is not None, factor_list1)
            if len(factor) == 0:
                factor1 = None
            else:
                factor1 = sum(factor)

    # factor3
    # 借贷账户信息   [1..1]
    EDA = getTable(data, "EDA", 1, 0)
    if EDA  == [{}]:
        factor3 = None
    elif EDA == 0:
        factor3 = 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0, 1)
        if ED01 == [{}]:
            factor3 = None
        elif ED01 == 0:
            factor3 = 0
        else:
            factor_list3 = []
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    # 还款信息段   [1..1]
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                        factor_list3.append(None)
                    elif ED01A == 0 or ED01B == 0:
                        factor_list3.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 借贷账户类型   [1..1]
                        ED01AD02 = ED01A[0].get('ED01AD02')
                        # 关闭日期   [1..1]
                        ED01AR03 = ED01A[0].get('ED01AR03')
                        # 到期日期 [1..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        # 还款表现信息 [0..*]
                        ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                        last_five_class = None
                        if ED01BH == [{}]:
                            factor_list3.append(None)
                        elif ED01BH == 0:
                            factor_list3.append(None)
                        else:
                            max_date = None
                            for j in ED01BH:
                                # 五级分类   [1..1]
                                ED01BD01 = j.get('ED01BD01')
                                # 信息报告日期   [1..1]
                                ED01BR01 = convertDataType(j.get('ED01BR01'), "date_time")
                                if ED01BR01 is not None and ED01BD01 is not None:
                                    if max_date is None:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD01
                                    elif ED01BR01 > max_date:
                                        max_date = ED01BR01
                                        last_five_class = ED01BD01
                        if ED01AD01 in null_type_list or ED01AD02 in null_type_list or last_five_class in null_type_list:
                            factor_list3.append(None)
                        else:
                            ED01AR02 = convertDataType(ED01AR02, "date_time")
                            # create_time = convertDataType(EA01AR01[:10], "date_time")
                            if ED01AD01 == "2" and ED01AD02 not in ("D2") and last_five_class in ("3", "4", "5", "6"):
                                if ED01AR03 in null_type_list:
                                    if ED01AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list3.append(1)
                                    elif five_years_ago < ED01AR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list3.append(1)
                                    else:
                                        factor_list3.append(0)
                                elif ED01AR03 not in null_type_list:
                                    ED01AR03 = convertDataType(ED01AR03, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list3.append(1)
                                    elif ED01AR03 not in null_type_list:
                                        if five_years_ago < ED01AR03.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list3.append(1)
                                        else:
                                            factor_list3.append(0)
                                    else:
                                        factor_list3.append(0)
                                else:
                                    factor_list3.append(0)
                            else:
                                factor_list3.append(0)
                except:
                    factor_list3.append(None)
                    continue
            factor = [i for i in factor_list3 if i is not None]
            # factor = filter(lambda x: x is not None, factor_list3)
            if len(factor) == 0:
                factor3 = None
            else:
                factor3 = sum(factor)

    # factor4
    # 借贷账户信息   [1..1]
    EDB = getTable(data, "EDB", 1, 0)
    if EDB == [{}]:
        factor4 = None
    elif EDB == 0:
        factor4 = 0
    else:
        # 担保账户信息明细单元   [0..*]
        ED04 = getTable(EDB[0], "ED04", 0, 1)
        if ED04  == [{}]:
            factor4 = None
        elif ED04 == 0:
            factor4 = 0
        else:
            factor_list4 = []
            for i in ED04:
                try:
                    # 在保责任信息段   [1..1]
                    ED04B = getTable(i, 'ED04B', 1, 1)
                    # 基本信息段   [1..1]
                    ED04A = getTable(i, 'ED04A', 1, 1)
                    if ED04B == [{}] or ED04A == [{}]:
                        factor_list4.append(None)
                    elif ED04B == 0 or ED04A == 0:
                        factor_list4.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED04BD01 = ED04B[0].get('ED04BD01')
                        # 五级分类   [1..1]
                        ED04BD02 = ED04B[0].get('ED04BD02')
                        # 关闭日期   [1..1]
                        ED04BR02 = ED04B[0].get('ED04BR02')
                        # 到期日期
                        ED04AR02 = ED04A[0].get('ED04AR02')
                        # 担保交易业务种类细分   [1..1]
                        ED04AD03 = ED04A[0].get('ED04AD03')
                        if ED04BD01 in null_type_list or ED04BD02 in null_type_list or ED04AD03 in null_type_list:
                            factor_list4.append(None)
                        else:
                            ED04AR02 = convertDataType(ED04AR02, "date_time")
                            # create_time = convertDataType(EA01AR01[:10], "date_time")
                            if ED04BD01 == "2" and ED04BD02 in ("3", "4", "5", "6") and \
                                    ED04AD03 in ("06", "09", "51", "61", "71", "72"):
                                if ED04BR02 in null_type_list:
                                    if ED04AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list4.append(1)
                                    elif five_years_ago < ED04AR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list4.append(1)
                                    else:
                                        factor_list4.append(0)
                                elif ED04BR02 not in null_type_list:
                                    ED04BR02 = convertDataType(ED04BR02, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list4.append(1)
                                    elif ED04BR02 not in null_type_list:
                                        if five_years_ago < ED04BR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list4.append(1)
                                        else:
                                            factor_list4.append(0)
                                    else:
                                        factor_list4.append(0)
                                else:
                                    factor_list4.append(0)
                            else:
                                factor_list4.append(0)
                except:
                    factor_list4.append(None)
                    continue
            factor = [i for i in factor_list4 if i is not None]
            # factor = filter(lambda x: x is not None, factor_list4)
            if len(factor) == 0:
                factor4 = None
            else:
                factor4 = sum(factor)

    # factor5
    # 借贷账户信息   [1..1]
    EDB = getTable(data, "EDB", 1, 0)
    if EDB == [{}]:
        factor5 = None
    elif EDB == 0:
        factor5 = 0
    else:
        # 担保账户信息明细单元   [0..*]
        ED04 = getTable(EDB[0], "ED04", 0, 1)
        if ED04 == [{}]:
            factor5 = None
        elif ED04 == 0:
            factor5 = 0
        else:
            factor_list5 = []
            for i in ED04:
                try:
                    # 在保责任信息段   [1..1]
                    ED04B = getTable(i, 'ED04B', 1, 1)
                    # 基本信息段   [1..1]
                    ED04A = getTable(i, 'ED04A', 1, 1)
                    if ED04A == [{}] or ED04B == [{}]:
                        factor_list5.append(None)
                    elif ED04A == 0 or ED04B == 0:
                        factor_list5.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED04BD01 = ED04B[0].get('ED04BD01')
                        # 五级分类   [1..1]
                        ED04BD02 = ED04B[0].get('ED04BD02')
                        # 余额   [1..1]
                        ED04BJ01 = ED04B[0].get('ED04BJ01')
                        # 关闭日期   [1..1]
                        ED04BR02 = ED04B[0].get('ED04BR02')
                        # 到期日期
                        ED04AR02 = ED04A[0].get('ED04AR02')
                        # 担保账户类型   [1..1]
                        ED04AD01 = ED04A[0].get('ED04AD01')
                        if ED04BD01 in null_type_list or ED04BD02 in null_type_list or \
                                isFloat(ED04BJ01) in null_type_list or ED04AD01 in null_type_list:
                            factor_list5.append(None)
                        else:
                            ED04AR02 = convertDataType(ED04AR02, "date_time")
                            # create_time = convertDataType(EA01AR01[:10], "date_time")
                            if ED04BD01 == "2" and ED04BD02 in ("3", "4", "5", "6") and \
                                    float(ED04BJ01) > 0 and ED04AD01 in ("G1", "G2", "G3"):
                                if ED04BR02 in null_type_list:
                                    if ED04AR02 in null_type_list or five_years_ago is None or five_years_ago == 0:
                                        factor_list5.append(1)
                                    elif five_years_ago < ED04AR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                        factor_list5.append(1)
                                    else:
                                        factor_list5.append(0)
                                elif ED04BR02 not in null_type_list:
                                    ED04BR02 = convertDataType(ED04BR02, "date_time")
                                    if five_years_ago is None or five_years_ago == 0:
                                        factor_list5.append(1)
                                    elif ED04BR02 not in null_type_list:
                                        if five_years_ago < ED04BR02.strftime("%Y%m%d") <= convertDataType(EA01AR01[:10], "date_time").strftime("%Y%m%d"):
                                            factor_list5.append(1)
                                        else:
                                            factor_list5.append(0)
                                    else:
                                        factor_list5.append(0)
                                else:
                                    factor_list5.append(0)
                            else:
                                factor_list5.append(0)
                except:
                    factor_list5.append(None)
                    continue
            factor = [i for i in factor_list5 if i is not None]
            # factor = filter(lambda x: x is not None, factor_list5)
            if len(factor) == 0:
                factor5 = None
            else:
                factor5 = sum(factor)

    # print(factor1,factor3,factor4,factor5)
    if factor1 is None and factor3 is None and factor4 is None and factor5 is None:
        return u'缺失值'
    else:
        factor1 = factor1 if factor1 is not None else 0
        factor3 = factor3 if factor3 is not None else 0
        factor4 = factor4 if factor4 is not None else 0
        factor5 = factor5 if factor5 is not None else 0
        factor = max(factor1, factor3, factor4, factor5)
        return factor


# if __name__ == '__main__':
#     file_obj = open(r'C:\Users\john\Desktop\samples\EC_DSJ_2D.json', 'r')
#     content = file_obj.read()
#     cQexecuteTime = ""
#     EC_DSJ_2D = json.loads(content, strict=False)
#     aa = R33_EC_PaidBusinessBadCheck()
#     print aa

result = R33_EC_PaidBusinessBadCheck()
